package org.springframework.springbootnettywebsokcetstarter.core;

import io.netty.channel.ChannelHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Import;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.springbootnettywebsokcetstarter.annotations.EnableWebSocketSever;
import org.springframework.springbootnettywebsokcetstarter.filter.WssServerInitialzer;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @version V1.0.0
 * @Title: WebSocketNetty
 * @Package com.dreamac.imwebsocketstarter.core
 * @Description: webSocket配置
 * @author: liuChuanqiang
 * @date: 2019/7/9 11:53
 */
@Component
@Import(WssServerInitialzer.class)
public class WebSocketNettyConfig  implements ApplicationListener<ContextRefreshedEvent> {

	public int getBossCount() {
		return bossCount;
	}

	public void setBossCount(int bossCount) {
		this.bossCount = bossCount;
	}

	public int getWorkerCount() {
		return workerCount;
	}

	public void setWorkerCount(int workerCount) {
		this.workerCount = workerCount;
	}

	public String getUri() {
		return uri;
	}

	public void setUri(String uri) {
		this.uri = uri;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public ChannelHandler getChannelHandler() {
		return channelHandler;
	}

	public void setChannelHandler(ChannelHandler channelHandler) {
		this.channelHandler = channelHandler;
	}

	/**
	 * @fields /读取yml中配置
	 * @author liuChuanqiang
	 */
	@Value("${spring.netty.web.boss-thread-count}")
	private int bossCount;

	@Value("${spring.netty.web.worker-thread-count}")
	private int workerCount;

	@Value("${spring.netty.web.uri}")
	private String uri;

	@Value("${spring.netty.web.port}")
	private int port;

	private ChannelHandler channelHandler;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		Map<String, Object> objectMap = event.getApplicationContext().getBeansWithAnnotation(EnableWebSocketSever.class);
		for (Object object : objectMap.values()) {
			Class<?> clazz = object.getClass();
			EnableWebSocketSever enableWebSocketSever = clazz.getAnnotation(EnableWebSocketSever.class);
			Class value = enableWebSocketSever.value();
			try {
				Object obj = value.newInstance();
				channelHandler = (ChannelHandler)obj;
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			return;
		}
	}
}
